﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Ruandao.Foundation.Service
{
    using Ruandao.Foundation.Service.DataAccess;

    public class TagService
    {
        // 几乎所有的函数都需要tagGroupId参数

        #region TagGroup

        public TagGroupData[] GetAllTagGroups()
        {
            //IList<TagGroupEntity> list = TagGroupEntity.SearchAllEntities();
            //List<TagGroupData> result = new List<TagGroupData>();
            //foreach (TagGroupEntity entity in list)
            //{
            //    TagGroupData data = NewGroupData(entity);
            //    result.Add(data);
            //}
            //return result.ToArray();
            throw new NotImplementedException();
        }

        public TagGroupData GetTagGroup(int tagGroupId)
        {
            //TagGroupEntity entity = TagGroupEntity.Fetch(tagGroupId);
            //if (entity == null)
            //    throw new TagServiceExcepiton("无效的标签组标识");

            //return NewGroupData( entity );
            throw new NotImplementedException();
        }

        //
        // 返回的是TagGroupId。可能抛出异常。
        //
        public int RegisterTagGroup(string title, 
                                    string description,
                                    Guid ownerGuid,
                                    int maxTags,
                                    int maxContents )
        {
            //TagGroupEntity entity = new TagGroupEntity();
            //entity.Title = title;
            //entity.Description = description;
            //entity.OwnerGuid = ownerGuid;
            //entity.MaxTags = maxTags;
            //entity.MaxContents = maxContents;
            //int isOk = entity.Save();
            //if (isOk != 1)
            //    throw new TagServiceExcepiton("内部错误：无法注册标签组服务。");

            //return entity.TagGroupId;
            throw new NotImplementedException();
        }

        public void DestroyTagGroup(int tagGroupId)
        {
            //TagGroupEntity.DestroyGroup(tagGroupId);
            throw new NotImplementedException();
        }

        public void ModifyTagGroup( int tagGroupId,
                                    string title,
                                    string description,
                                    Guid ownerGuid,
                                    int maxTags,
                                    int maxContents)
        {
            //TagGroupEntity entity = TagGroupEntity.Fetch(tagGroupId);
            //entity.Title = title;
            //entity.Description = description;
            //entity.OwnerGuid = ownerGuid;
            //entity.MaxTags = maxTags;
            //entity.MaxContents = maxContents;
            //int isOk = entity.Save();
            //if (isOk != 1)
            //    throw new TagServiceExcepiton("内部错误：修改标签组信息发生异常。");
            throw new NotImplementedException();
        }

        #endregion

        #region TagCategorty


        #endregion

        #region Tag

        /*
        public TagData[] GetAllTags(int tagGroupId)
        {
        }

        public TagData GetTag(int tagGroupId, string tagName)
        {
        }

        public TagData GetTag(int tagId)
        {
        }

        //
        // 根据TagGroup中的设置，如果参数非法则抛出异常。
        //
        public void ModigyTag(int tagId, string newTagName, string newDescription, bool isSystem, int tagLevel)
        {
        }

        public TagData CreateNewTag(int tagGroupId, string tagName, string newDescription, bool isSystem, int tagLevel)
        {
        }


        public void DeleteTag(int tagGroupId, string tagName)
        {
        }

        public void DeleteTag(int tagId)
        {
        }
        */
        #endregion


        #region Content

        /// <summary>
        /// 提交内容的标签信息。如果标签尚未存在，则先添加，否则只需添加内容索引信息。
        /// 注意，允许提交不包括任何标签的内容。比如只能用全文检索的内容。
        /// 先查找ContentId的内容是否已经存在，如果已经存在则调用修改内容的函数，
        /// 否则添加新的内容。
        /// </summary>
        /// <param name="content">内容信息</param>
        /// <param name="tags">内容所属的所有标签，可以为null，表示删除所有的标签。</param>
        public void SetContentTags(int tagGroupId, int contentId, string[] tags, int rank)
        {
            //// 删除原来的标签设置。
            //int[] tagIndexIds = TagContentIndexEntity.SearchTagIndex(tagGroupId, contentId);
            //foreach (int id in tagIndexIds)
            //{
            //    DetachContentIndex(id, contentId);
            //}

            //// 首先：根据classNames得到classId的数组
            //int[] tagIds = TagEntity.GetTagIds(tagGroupId, tags);

            //// 其次：重要！缓存索引项时，必须classId1 < classId2 < classId3
            //Array.Sort(tagIds);

            //// 然后：建立内容的多级标签索引。
            //int count = tagIds.Length;
            //for (int i = 0; i < count; i++)
            //{
            //    AttachContentIndex(tagGroupId, contentId, rank, tagIds[i]);
            //    for (int j = i + 1; j < count; j++)
            //    {
            //        AttachContentIndex(tagGroupId, contentId, rank, tagIds[i], tagIds[j] );
            //        for (int k = j + 1; k < count; k++)
            //        {
            //            AttachContentIndex(tagGroupId, contentId, rank, tagIds[i], tagIds[j], tagIds[k] );
            //            for (int m = k + 1; m < count; m++)
            //            {
            //                AttachContentIndex(tagGroupId, contentId, rank, tagIds[i], tagIds[j], tagIds[k], tagIds[m] );
            //                for (int n = m + 1; n < count; n++)
            //                {
            //                    AttachContentIndex(tagGroupId, contentId, rank, tagIds[i], tagIds[j], tagIds[k], tagIds[m], tagIds[n] );
            //                    for( int a = n+1; a < count; a++ )
            //                    {
            //                        AttachContentIndex(tagGroupId, contentId, rank, tagIds[i], tagIds[j], tagIds[k], tagIds[m], tagIds[n], tagIds[a] );
            //                        for( int b = a+1; b<count; b++ )
            //                        {
            //                            AttachContentIndex(tagGroupId, contentId, rank, tagIds[i], tagIds[j], tagIds[k], tagIds[m], tagIds[n], tagIds[a], tagIds[b]);
            //                            for (int c = b + 1; c < count; c++ )
            //                            {
            //                                AttachContentIndex(tagGroupId, contentId, rank, tagIds[i], tagIds[j], tagIds[k], tagIds[m], tagIds[n], tagIds[a], tagIds[b], tagIds[c] );
            //                            }
            //                        }
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}

            //ContentTagsEntity content = ContentTagsEntity.Fetch(tagGroupId, contentId);
            //if (content == null)
            //{
            //    content = new ContentTagsEntity();
            //    content.TagGroupId = tagGroupId;
            //    content.ContentId = contentId;
            //}
            //content.TagIds = tagIds;
            //content.Rank = rank;
            //content.Save();
            throw new NotImplementedException();

        }

        /// <summary>
        /// 需要同时设置所有的索引记录中的rank数值。
        /// </summary>
        /// <param name="contentId"></param>
        public void SetContentRank(int tagGroupId, int contentId, int rank)
        {
            //ContentTagsEntity.SetRank(tagGroupId, contentId, rank);
            throw new NotImplementedException();
        }

        public int[] Search(int tagGroupId, string[] tagTitles)
        {
            //int[] tagIds = TagEntity.GetTagIds(tagGroupId, tagTitles);
            //return TagIndexEntity.FetchByTags(tagIds).CachedContentIds;
            throw new NotImplementedException();
        }

        // 搜索出某一个类别下的标签，以及他们所拥有的内容数量。
        public Dictionary<string, int> SearchSubTags(int tagGroupId, string category)
        {
            throw new NotImplementedException();
        }

        // 搜索出含有内容的下一级子标签，以及他们所拥有的内容数量。
        public Dictionary<string, int> SearchSubTags(int tagGroupId, string[] tagTitles)
        {
            //int[] tagIds = TagEntity.GetTagIds(tagGroupId, tagTitles);
            //List<TagIndexEntity> list = TagIndexEntity.SearchSubTags(tagIds);

            //Dictionary<string,int> dic = new Dictionary<string,int>();
            //foreach (TagIndexEntity e in list)
            //{
            //    int id = GetIdNumber(e,tagIds.Length);
            //    dic.Add(TagEntity.Fetch(id).TagName, e.ContentAmount);
            //}
            
            //return dic;           
            throw new NotImplementedException();
        }

        // GettyId0、1、2、... 7。
        private static int GetIdNumber( TagIndex entity,int number)
        {
            switch (number)
            {
                //case 0: return entity.TagId0;
                case 1: return entity.TagId1;
                case 2: return entity.TagId2;
                case 3: return entity.TagId3;
                case 4: return entity.TagId4;
                case 5: return entity.TagId5;
                case 6: return entity.TagId6;
                case 7: return entity.TagId7; 
                default:
                    return entity.TagId7;
            }
        }


        static private void AttachContentIndex(
            int tagGroupId, 
            int contentId, 
            int rank,
            params int[] tagIds )
        {
            //TagIndexEntity e = TagIndexEntity.FetchByTags(tagIds);

            //if (e == null)
            //{
            //    int number = tagIds.Length; ;
            //    int[] ids = new int[8];
            //    for (int i = 0; i < number; i++)
            //    {
            //        ids[i] = tagIds[i];
            //    }
            //    e = new TagIndexEntity();
            //    e.TagGroupId = tagGroupId;
            //    e.TagNumber = number;
            //    e.TagId0 = ids[0];
            //    e.TagId1 = ids[1];
            //    e.TagId2 = ids[2];
            //    e.TagId3 = ids[3];
            //    e.TagId4 = ids[4];
            //    e.TagId5 = ids[5];
            //    e.TagId6 = ids[6];
            //    e.TagId7 = ids[7];
            //    e.AccessCounter = 1;
            //    e.LastAccessTime = DateTime.Now;
            //    e.ContentAmount = 1;
            //    e.CachedContentIds = new int[] { contentId };
            //    e.Save();

            //    TagContentIndexEntity tc = new TagContentIndexEntity();
            //    tc.TagIndexId = e.TagIndexId;
            //    tc.Rank = rank;
            //    tc.ContentId = contentId;
            //    tc.Save();
            //}
            //else
            //{
            //    TagContentIndexEntity tc = new TagContentIndexEntity();
            //    tc.TagIndexId = e.TagIndexId;
            //    tc.Rank = rank;
            //    tc.ContentId = contentId;
            //    tc.Save();

            //    int[] contentIds = TagContentIndexEntity.SearchByTagIndex(e.TagIndexId);
            //    e.ContentAmount = contentIds.Length;
            //    e.CachedContentIds = contentIds;
            //    e.AccessCounter++;
            //    e.LastAccessTime = DateTime.Now;
            //    e.Save();
            //}
            throw new NotImplementedException();
        }

        static private void DetachContentIndex(
            int tagIndexId,
            int contentId )
        {
            //TagIndexEntity e = TagIndexEntity.Fetch(tagIndexId);
            //if (e != null)
            //{
            //    int result = TagContentIndexEntity.Delete(tagIndexId, contentId);

            //    int[] contentIds = TagContentIndexEntity.SearchByTagIndex(e.TagIndexId);
            //    e.ContentAmount = contentIds.Length;
            //    e.CachedContentIds = contentIds;
            //    e.AccessCounter++;
            //    e.LastAccessTime = DateTime.Now;
            //    e.Save();
            //}
            throw new NotImplementedException();
        }

        #endregion

        # region  最初的设计是一个内容可以支持任意数量的标签，此时，需要多次检索。
        /* 以注释形式保留这些代码，该算法有其独到之处，供今后参考。
        /// <summary>
        /// 任意标签数量的查询，当条件多于5个时，需要用多次搜索然后对结果快速求交。
        /// </summary>
        /// <param name="tagTitles">检索条件。</param>
        /// <returns>搜索到的内容项的Id数组。</returns>
        public int[] Search(int tagGroupId, string[] tagTitles)
        {
            int[] tagIds = TagEntity.GetTagIds(tagGroupId,tagTitles);

            int number = tagIds.Length;
            int[] contents = new int[0];
            int[] tempContents;

            for (int i = 0; i < number; i = i + 5)
            {
                int[] searchIds;
                if (i == 0)
                {
                    searchIds = GetSubTagIds(tagIds, 0);
                    contents = TagsContentsEntity.GetEntity(clientId, contentType, searchIds).ContentIds;
                }
                else
                {
                    if (number - i - 5 < 0)
                    {
                        searchIds = GetSubTagIds(tagIds, i + (number - i - 5));
                    }
                    else
                    {
                        searchIds = GetSubTagIds(tagIds, i);
                    }
                    tempContents = TagsContentsEntity.GetEntity(clientId, contentType, searchIds).ContentIds;
                    contents = Ruandao.Foundation.Service.ArithmeticKit.IntArrayIntersection(contents, tempContents);
                }
            }

            return contents;
        }

        */
        #endregion
    }
}
